<template>
  <div>
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>

    <el-card>
      <el-row>
        <el-col>
          <el-button type="primary">添加角色</el-button>
        </el-col>
      </el-row>
      <el-table :data="roleslist" border stripe>
        <el-table-column type="expand">
          <template slot-scope="scope">
            <el-row
              v-for="(item1, index1) in scope.row.children"
              :key="item1.id"
              :class="['bdbottom', index1 === 0 ? 'bdtop' : '', 'vcenter']"
            >
              <!-- :class=[]这个动态class，需要学习，新知识 -->
              <el-col :span="5"
                ><el-tag
                  closable
                  @close="removeRightById(scope.row, item1.id)"
                  type="primary"
                  >{{ item1.authName }}</el-tag
                ><i class="el-icon-caret-right"></i
              ></el-col>
              <el-col :span="19">
                <el-row
                  v-for="(item2, index2) in item1.children"
                  :key="item2.id"
                  :class="[index2 === 0 ? '' : 'bdtop', 'vcenter']"
                >
                  <el-col :span="6"
                    ><el-tag
                      closable
                      @close="removeRightById(scope.row, item2.id)"
                      type="success"
                      >{{ item2.authName }}</el-tag
                    ><i class="el-icon-caret-right"></i
                  ></el-col>
                  <el-col :span="18">
                    <span v-for="item3 in item2.children" :key="item3.id">
                      <el-tag
                        closable
                        @close="removeRightById(scope.row, item3.id)"
                        type="warning"
                        >{{ item3.authName }}</el-tag
                      >
                    </span>
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
            <!-- <pre>{{scope.row}}</pre> -->
            <!-- pre结构化显示数据 -->
          </template>
        </el-table-column>
        <el-table-column type="index"></el-table-column>
        <el-table-column label="角色名称" prop="roleName"></el-table-column>
        <el-table-column label="角色描述" prop="roleDesc"></el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button size="mini" type="primary" icon="el-icon-edit"
              >编辑</el-button
            >
            <el-button size="mini" type="danger" icon="el-icon-delete"
              >删除</el-button
            >
            <el-button
              @click="showSetRightDialog(scope.row)"
              size="mini"
              type="warning"
              icon="el-icon-setting"
              >分配权限</el-button
            >
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <!--分配权限对话框  -->
    <el-dialog
      title="分配权限"
      :visible.sync="setRightDialogVisible"
      width="50%"
    >
      <el-tree :data="rightsList" :props="treeProps" show-checkbox node-key="id" default-expand-all :default-checked-keys="defKeys" ref='treeRef'></el-tree>
      <span slot="footer" class="dialog-footer">
        <el-button @click="setRightDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="allotRights" 
          >确 定</el-button
        >
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      roleslist: [],
      setRightDialogVisible:false,
      rightsList:[], //所有权限
      treeProps: {  //定义树形结构的父子传递字段和名称显示字段
          children: 'children',
          label: 'authName'
        },
      defKeys:[], //默认选中的节点id值数组
      roleId:'' //弹出对话矿的那个按钮对应的角色id

    }
  },

  created() {
    this.getRolesList()
  },
  methods: {
    async getRolesList() {
      const { data: res } = await this.$http.get('roles')
      if (res.meta.status !== 200) return this.$message.error('获取数据失败')
      this.roleslist = res.data
      console.log(this.roleslist)
    },
    async removeRightById(role, rightId) {
      const confirmResult = await this.$confirm(
        '此操作将永久删除该文件, 是否继续?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        }
      ).catch((err) => err)
      if (confirmResult !== 'confirm') {
        return this.$message.info('取消删除')
      }
      // console.log('确认删除');
      const { data: res } = await this.$http.delete(
        `roles/${role.id}/rights/${rightId}`
      )
      if (res.meta.status !== 200) return this.$message.info('删除失败')
      this.$message.success('删除成功')
      // this.getRolesList() //如果这么写，权限树会关闭，不建议这么写
      role.children = res.data
      //上面这句直接改执行函数的参数，调用函数那边的数据竟然会跟着改，神奇，vue的不可思议
    },
    async showSetRightDialog(role) {
      this.roleId=role.id
      this.defKeys.splice(0,this.defKeys.length) //清空数组
      const {data:res}= await this.$http.get('rights/tree')
      if(res.meta.status!==200) return this.$message.info('数据获取失败')
      this.rightsList=res.data
      this.getLeafKeys(role,this.defKeys)
      this.setRightDialogVisible=true
    },
    getLeafKeys(node,arr){ //生成默认选中节点数组
    if(!node.children)return arr.push(node.id)
    node.children.forEach(item=>this.getLeafKeys(item,arr))
    },
    async allotRights(){
      const keys= [...this.$refs.treeRef.getCheckedKeys(),...this.$refs.treeRef.getHalfCheckedKeys()]
      const idStr=keys.join(',')
      console.log(idStr);
      const{data:res}= await this.$http.post(`roles/${this.roleId}/rights    `,{rids:idStr})
      if(res.meta.status!==200) {return this.$message.error("设置失败")}
      else{this.$message.success('设置成功')
      this.getRolesList()}
      this.setRightDialogVisible = false
    }
  },
}  //
</script>

<style scopted>
.el-tag {
  margin: 7px;
}
.bdtop {
  border-top: 1px solid #eee;
}
.bdbottom {
  border-bottom: 1px solid #eee;
}
.vcenter {
  display: flex;
  align-items: center;
}
</style>